import _thread
from datetime import datetime
from time import sleep

import psutil
import win32gui
import win32process
from PIL import Image, ImageGrab
from win10toast import ToastNotifier

from ..entity import Log
from ..config import config
from .abc import OS, Notifier, TimeLogger
# import pyautogui # !
import os


class WindowsTimeLogger(TimeLogger):
    def __init__(self) -> None:
        pass

    def get_log(self) -> Log:
        log = Log()
        log.time = datetime.now()

        # 获取最前活动窗口的应用程序名
        window = win32gui.GetForegroundWindow()
        log.title = win32gui.GetWindowText(window)

        pid = win32process.GetWindowThreadProcessId(window)  # 获取窗口线程ID+进程ID
        log.program = psutil.Process(pid[-1]).name()  # 获取进程名
        return log

    def save_current_capture(self) -> str:
        img = ImageGrab.grab()
        width, height = img.size
        img = img.resize((int(width * config.capture_scale), int(height * config.capture_scale)))
        img_path = os.path.join(config.capture_path, datetime.now().strftime('%Y_%m_%d_%H_%M_%S.png'))
        img.save(img_path)
        return img_path


class WindowsNotifier(Notifier):
    icon_path = None

    def __init__(self) -> None:
        self.toaster = ToastNotifier()

    def notify_by_toast(self, msg: str, title: str, duration_second: int) -> None:
        _thread.start_new_thread(self.toaster.show_toast, (title, msg, self.icon_path, duration_second, True))
        # seems that max(duration_second) = 10
        sleep(1.)  # TODO remove this sleep when the app is running

    def notify_by_window(self, msg: str, title: str, duration_second: int) -> None:
        raise NotImplementedError()


class WindowsOS(OS):
    def __init__(self) -> None:
        self._notifier = WindowsNotifier()
        self._time_logger = WindowsTimeLogger()

    @property
    def notifier(self) -> Notifier:
        return self._notifier

    @property
    def time_logger(self) -> TimeLogger:
        return self._time_logger
